/* eslint-disable no-new */
import EventEmitter from "eventemitter3";
import * as PIXI from "pixi.js";
import { gsap } from "gsap";
import { PixiPlugin } from "gsap/PixiPlugin.js";
import { RedPackage } from "./components/RedPackage";
import { Star } from "./components/Star";
import { Score } from "./components/Score";
import { Timer } from "./components/Timer";

gsap.registerPlugin(PixiPlugin);

export class App extends EventEmitter {
  app;

  score;

  timer;

  redPkgTimer;

  starTimer;

  // 创建星星的速率
  starFrequency = 800;

  // 创建红包的速率
  redPackageFrequency = 1000;

  constructor(container, gameConfig, canvasConfig) {
    super();
    this.score = new Score();
    this.init(container);
  }

  init(container) {
    this.app = new PIXI.Application({
      antialias: true,
      autoDensity: true,
      resolution: 2,
      width: window.innerWidth,
      height: window.innerHeight,
      backgroundColor: 0x000000,
      backgroundAlpha: 0,
      ...this.canvasConfig,
    });
    container?.appendChild(this.app.view);
  }

  start() {
    const animations = this.gameConfig?.animations;

    if (this.app) {
      this.createTimer();

      this.redPkgTimer = setInterval(() => {
        this.createRedPackage();
      }, animations?.redPackageFrequency || this.redPackageFrequency);

      this.starTimer = setInterval(() => {
        this.createStar();
      }, animations?.starFrequency || this.starFrequency);
    }
  }

  // 创建红包
  createRedPackage() {
    if (!this.app) return;
    let redPackage = new RedPackage(this.app, this.gameConfig);
    redPackage.on("redPackageClick", this.onRedPackageClick.bind(this));
    redPackage.create();
    redPackage.drop();
    redPackage = null;
  }

  // 创建星星
  createStar() {
    if (!this.app) return;
    let star = new Star(this.app, this.gameConfig);
    star.create();
    star.drop();
    star = null;
  }

  createTimer() {
    this.timer = new Timer(this.app, this.gameConfig);
    this.timer.start();
    this.timer.on("timeEnd", () => {
      this.onTimeEnd();
      this.destroy();
    });
  }

  // 红包点击
  onRedPackageClick(cb) {
    const score = this.score.add();
    cb(score);
  }

  //    游戏结束
  onTimeEnd() {
    const score = this.score.get();
    this.emit("timeEnd", score);
  }

  //   销毁创建的所有实例和画布
  destroy() {
    clearInterval(this.redPkgTimer);
    clearInterval(this.starTimer);
    this.redPkgTimer = null;
    this.starTimer = null;

    while (this.app?.stage.children[0]) {
      this.app.stage.removeChild(this.app.stage.children[0]);
    }

    this.app?.destroy(true);
    this.app?.renderer?.destroy(true);
  }
}
